//引入请求
import {
  getDetailRequest,
  getLoginRequest,
  getUserInfoRequest,
  getLogoutRequest,
} from "@/api/index";

import getUserTempId from "@/utils/userTempId";

const state = {
  detailInfo: {},
  userTempId: getUserTempId(),
  token: localStorage.getItem("user_Token"),
  nickName: "",
};
const mutations = {
  setDetailInfo(state, value) {
    state.detailInfo = value;
  },
  //设置token
  setToken(state, value) {
    state.token = value;
  },
  //设置用户名
  setUserName(state, nickName) {
    state.nickName = nickName;
  },
  //推出登入清空token
  setLogout(state) {
    state.token = "";
    state.nickName = "";
    localStorage.removeItem("user_Token");
  },
};

const actions = {
  async getDetailInfo({ commit }, skuId) {
    const re = await getDetailRequest(skuId);
    commit("setDetailInfo", re);
  },
  //获取token回调
  async getTokenInfo({ commit }, userInfo) {
    const re = await getLoginRequest(userInfo);
    commit("setToken", re.token);
    //请求到token之后,要把token持久化到本地中,否则刷新以后vuex就没有数据了,用户需要重新登录
    localStorage.setItem("user_Token", re.token);
  },
  //获取用户名
  async getUserName({ commit }) {
    try {
      const re = await getUserInfoRequest();
      commit("setUserName", re.nickName);
    } catch (e) {
      //在使用token发送请求的时候,如果token过期,则会抛出错误,被这里接受,我们可以清除掉token
      localStorage.removeItem("user_Token");
      //如果这里请求报错,则返回一个失败的promise实例,则dispatch方法就会返回这个失败的实例
      return Promise.reject();
    }
  },
  //退出登入
  async getLogout({ commit }) {
    await getLogoutRequest();
    commit("setLogout");
  },
};

const getters = {
  categoryView(state) {
    return state.detailInfo.categoryView || {};
  },
  spuSaleAttrList(state) {
    return state.detailInfo.spuSaleAttrList || [];
  },
  skuInfo(state) {
    return state.detailInfo.skuInfo || {};
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
